import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Query,
  UseInterceptors,
  UploadedFile,
  ParseIntPipe,
  BadRequestException,
  Res,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiConsumes,
  ApiBody,
} from '@nestjs/swagger';
import { Response } from 'express';
import * as XLSX from 'xlsx';
import { MatchesService } from './matches.service';
import { CreateMatchDto } from './dto/create-match.dto';
import { UpdateMatchDto } from './dto/update-match.dto';
import { QueryMatchDto } from './dto/query-match.dto';
import { Match } from './entities/match.entity';
import { Public } from 'src/common/decorators/public.decorator';

@ApiTags('比赛管理')
@Controller('matches')
export class MatchesController {
  constructor(private readonly matchesService: MatchesService) {}

  @ApiOperation({ summary: '创建比赛' })
  @ApiResponse({ status: 201, description: '创建成功', type: Match })
  @Post()
  create(@Body() createMatchDto: CreateMatchDto) {
    return this.matchesService.create(createMatchDto);
  }

  @ApiOperation({ summary: '获取比赛列表' })
  @ApiResponse({ status: 200, description: '获取成功' })
  @Get()
  findAll(@Query() queryDto: QueryMatchDto) {
    return this.matchesService.findAll(queryDto);
  }

  @ApiOperation({ summary: '根据ID获取比赛详情' })
  @ApiResponse({ status: 200, description: '获取成功', type: Match })
  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number) {
    return this.matchesService.findOne(id);
  }

  @ApiOperation({ summary: '更新比赛' })
  @ApiResponse({ status: 200, description: '更新成功', type: Match })
  @Patch(':id')
  update(
    @Param('id', ParseIntPipe) id: number,
    @Body() updateMatchDto: UpdateMatchDto,
  ) {
    return this.matchesService.update(id, updateMatchDto);
  }

  @ApiOperation({ summary: '删除比赛' })
  @ApiResponse({ status: 200, description: '删除成功' })
  @Delete(':id')
  remove(@Param('id', ParseIntPipe) id: number) {
    return this.matchesService.remove(id);
  }

  @ApiOperation({ summary: '批量删除比赛' })
  @ApiResponse({ status: 200, description: '批量删除成功' })
  @ApiBody({
    description: '比赛ID数组',
    schema: {
      type: 'object',
      properties: {
        ids: {
          type: 'array',
          items: { type: 'number' },
          example: [1, 2, 3],
        },
      },
    },
  })
  @Delete()
  removeBatch(@Body('ids') ids: number[]) {
    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      throw new BadRequestException('请提供有效的ID数组');
    }
    return this.matchesService.removeBatch(ids);
  }

  @ApiOperation({ summary: '导入Excel文件' })
  @Public()
  @ApiResponse({ 
    status: 200, 
    description: '导入成功',
    schema: {
      type: 'object',
      properties: {
        success: { type: 'number', description: '成功导入的比赛数量' },
        failed: { type: 'number', description: '导入失败的比赛数量' },
        errors: { 
          type: 'array', 
          items: { type: 'string' },
          description: '错误信息列表' 
        },
      },
    },
  })
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    description: 'Excel文件',
    schema: {
      type: 'object',
      properties: {
        file: {
          type: 'string',
          format: 'binary',
        },
      },
    },
  })
  @Post('import')
  @UseInterceptors(FileInterceptor('file'))
  async importExcel(@UploadedFile() file: Express.Multer.File) {
    console.log('接收到文件上传请求，文件信息:', {
      hasFile: !!file,
      filename: file?.originalname,
      mimetype: file?.mimetype,
      size: file?.size,
      hasBuffer: !!file?.buffer,
      bufferLength: file?.buffer?.length
    });
    
    if (!file) {
      throw new BadRequestException('请上传Excel文件');
    }
    
    if (!file.buffer) {
      throw new BadRequestException('文件缓冲区为空，文件上传可能失败');
    }

    // 验证文件类型
    const allowedMimeTypes = [
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
      'application/vnd.ms-excel', // .xls
    ];

    if (!allowedMimeTypes.includes(file.mimetype)) {
      throw new BadRequestException('只支持Excel文件格式（.xlsx, .xls）');
    }

    // 验证文件大小（限制为10MB）
    const maxSize = 10 * 1024 * 1024; // 10MB
    if (file.size > maxSize) {
      throw new BadRequestException('文件大小不能超过10MB');
    }

    return this.matchesService.importExcel(file.buffer);
  }

  @ApiOperation({ summary: '导入比分更新Excel文件' })
  @Public()
  @ApiResponse({ 
    status: 200, 
    description: '比分更新导入成功',
    schema: {
      type: 'object',
      properties: {
        success: { type: 'number', description: '成功更新的比赛数量' },
        failed: { type: 'number', description: '更新失败的比赛数量' },
        errors: { 
          type: 'array', 
          items: { type: 'string' },
          description: '错误信息列表' 
        },
      },
    },
  })
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    description: '比分更新Excel文件',
    schema: {
      type: 'object',
      properties: {
        file: {
          type: 'string',
          format: 'binary',
        },
      },
    },
  })
  @Post('import-score')
  @UseInterceptors(FileInterceptor('file'))
  async importScoreUpdate(@UploadedFile() file: Express.Multer.File) {
    console.log('接收到比分更新文件上传请求，文件信息:', {
      hasFile: !!file,
      filename: file?.originalname,
      mimetype: file?.mimetype,
      size: file?.size,
      hasBuffer: !!file?.buffer,
      bufferLength: file?.buffer?.length
    });
    
    if (!file) {
      throw new BadRequestException('请上传Excel文件');
    }
    
    if (!file.buffer) {
      throw new BadRequestException('文件缓冲区为空，文件上传可能失败');
    }

    // 验证文件类型
    const allowedMimeTypes = [
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
      'application/vnd.ms-excel', // .xls
    ];

    if (!allowedMimeTypes.includes(file.mimetype)) {
      throw new BadRequestException('只支持Excel文件格式（.xlsx, .xls）');
    }

    // 验证文件大小（限制为10MB）
    const maxSize = 10 * 1024 * 1024; // 10MB
    if (file.size > maxSize) {
      throw new BadRequestException('文件大小不能超过10MB');
    }

    return this.matchesService.importScoreUpdate(file.buffer);
  }

  @ApiOperation({ summary: '下载Excel模板' })
  @ApiResponse({ status: 200, description: '下载成功' })
  @Public()
  @Get('template/download')
  downloadTemplate(@Res() res: Response) {
    // 创建Excel模板数据 - 根据实际业务场景，北单和竞彩数据分开
    const templateData = [
      // 竞彩数据示例
      {
        '竞彩编号': '135',
        '北单编号': '',
        '开赛时间': '2025-07-14 23:00:00',
        '赛事': '分组',
        '主队': '埃尔维斯',
        '客队': '瓦萨',
        '竞彩单关': '0',
        '竞彩让球': 0,
        '北单让球': '',
        '胜': 2.91,
        '平': 4.33,
        '负': 2.34,
        'ID': '5558764'
      },
      {
        '竞彩编号': '135',
        '北单编号': '',
        '开赛时间': '2025-07-14 23:00:00',
        '赛事': '分组',
        '主队': '埃尔维斯',
        '客队': '瓦萨',
        '竞彩单关': '-1',
        '竞彩让球': -1,
        '北单让球': '',
        '胜': 2.22,
        '平': 3.40,
        '负': 2.60,
        'ID': '5558764'
      },
      // 北单数据示例
      {
        '竞彩编号': '',
        '北单编号': '周一001',
        '开赛时间': '2025-07-14 23:00:00',
        '赛事': '分组',
        '主队': '埃尔维斯',
        '客队': '瓦萨',
        '竞彩单关': '',
        '竞彩让球': '',
        '北单让球': 0,
        '胜': 1.37,
        '平': 4.45,
        '负': 5.75,
        'ID': '5558764'
      },
      {
        '竞彩编号': '',
        '北单编号': '周一001',
        '开赛时间': '2025-07-14 23:00:00',
        '赛事': '分组',
        '主队': '埃尔维斯',
        '客队': '瓦萨',
        '竞彩单关': '',
        '竞彩让球': '',
        '北单让球': -1,
        '胜': 2.22,
        '平': 3.40,
        '负': 2.60,
        'ID': '5558764'
      }
    ];

    // 创建工作簿
    const workbook = XLSX.utils.book_new();
    const worksheet = XLSX.utils.json_to_sheet(templateData);
    
    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(workbook, worksheet, '比赛数据');
    
    // 生成Excel文件缓冲区
    const excelBuffer = XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' });
    
    // 设置响应头
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.setHeader('Content-Disposition', 'attachment; filename="matches_template.xlsx"');
    
    // 发送文件
    res.send(excelBuffer);
  }

  @ApiOperation({ summary: '下载比分更新Excel模板' })
  @ApiResponse({ status: 200, description: '下载成功' })
  @Public()
  @Get('template/score-update')
  downloadScoreUpdateTemplate(@Res() res: Response) {
    // 创建比分更新Excel模板数据
    const templateData = [
      {
        '竞彩编号': '135',
        '北单编号': '',
        '开赛时间': '2025-07-14 23:00:00',
        '赛事': '分组',
        '主队': '埃尔维斯',
        '客队': '瓦萨',
        '竞彩单关': '0',
        '竞彩让球': 0,
        '北单让球': '',
        '胜': 2.91,
        '平': 4.33,
        '负': 2.34,
        'ID': '5558764',
        '主比分': 2,
        '客比分': 1,
        '赛果': 'win'
      },
      {
        '竞彩编号': '136',
        '北单编号': '',
        '开赛时间': '2025-07-15 20:00:00',
        '赛事': '英超',
        '主队': '曼联',
        '客队': '利物浦',
        '竞彩单关': '-1',
        '竞彩让球': -1,
        '北单让球': '',
        '胜': 2.22,
        '平': 3.40,
        '负': 2.60,
        'ID': '5558765',
        '主比分': 1,
        '客比分': 1,
        '赛果': 'draw'
      }
    ];

    // 创建工作簿
    const workbook = XLSX.utils.book_new();
    const worksheet = XLSX.utils.json_to_sheet(templateData);
    
    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(workbook, worksheet, '比分更新数据');
    
    // 生成Excel文件缓冲区
    const excelBuffer = XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' });
    
    // 设置响应头
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.setHeader('Content-Disposition', 'attachment; filename="score_update_template.xlsx"');
    
    // 发送文件
    res.send(excelBuffer);
  }
}